var cheerio = require('cheerio')
var http = require('http')
var fs = require('fs')
var rp = require('request-promise')
var moment = require('moment')
var cheerio = require('cheerio')
var iconv = require('iconv-lite')
var BufferHelper = require('bufferhelper');

var config = require('./config.js')
var util = require('./util/_default.js')
var xdl = require('./xdl.js')

var helper = util.helper
var dbHelper = util.dbHelper
var logHelper = util.logHelper
var yzmHelper = util.yzmHelper

//logHelper.init()

var args = process.argv.splice(2)

var tableId, rowArr = []

if (args.length == 1) {
    tableId = args[0]
    main()
} else {
    console.log('参数异常！')
}

function main() {
    if (rowArr.length <= 0) {
        var sql = 'select top 100 * from sfda' + tableId + 'Detail where cpStatus=0'
        var param = {}
        dbHelper.qv(sql, param, function (rows) {
            if (rows.length == 0) {
                process.exit(0)
            } else {
                rowArr = rows
                getdetail(rowArr.shift())
            }
        }, function (err) {
            var msg = '获取采集任务出错。Error:' + err
            console.log(msg)
        })
    } else {
        getdetail(rowArr.shift())
    }
}

function getdetail(row) {
    console.log('批次[' + row.cpId + ']获取总页数信息')
    var url = 'http://appcfda.drugwebcn.com/datasearch/QueryRecord?tableId=' + tableId + '&searchF=ID&searchK=' + row.cpId
    var req = http.get(url, function (res) {
        var bufferHelper = new BufferHelper();
        res.on('data', function (chunk) {
            bufferHelper.concat(chunk);
        });
        res.on('end', function () {
            var detail = iconv.decode(bufferHelper.toBuffer(), 'GBK');
            var sql = 'update sfda' + tableId + 'Detail set cpDetail=@detail,cpStatus=9,cpTime=getdate() where cpid=@id'
            var param = {
                id: row.cpId,
                detail: detail
            }
            dbHelper.qv(sql, param, function () {
                main()
            }, function (err) {
                var msg = '数据保存出错。Error:' + err
                console.log('批次[' + row.cpId + ']' + msg)
                getdetail(row)
            })
        });
        res.on('error', function (err) {
            console.log('批次[' + row.cpId + ']' + err)
            getdetail(row)
        });
    })

    req.on('error', function (err) {
        console.log('批次[' + row.cpId + ']' + err)
        getdetail(row)
    });
}

